<template>
  <view class="table-page-container">
    <!-- 筛选栏 -->
    <view class="header" v-if="showHeader">
      <sv-table-header @submit="submitFilter"></sv-table-header>
    </view>
    <!-- 表格头部控制栏 -->
    <view class="control">
      <el-button type="primary" plain size="small" :icon="Plus" @click="add">新增</el-button>
      <el-button type="danger" plain size="small" :icon="Delete" @click="selectionRemove">
        批量删除
      </el-button>
      <view style="flex: 1"></view>
      <el-button
        type="primary"
        link
        :icon="showHeader ? View : Hide"
        @click="showHeader = !showHeader"
      ></el-button>
      <el-button type="primary" link :icon="RefreshRight" @click="refresh"></el-button>
    </view>
    <!-- 表格主体 -->
    <el-table
      class="sv-el-table"
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" width="50" fixed="left" />
      <el-table-column prop="sort" label="序号" align="center" :width="60"></el-table-column>
      <el-table-column prop="icon" label="图标" align="center" :width="80">
        <template #default="scope">
          <text class="text-xxl" :class="scope.row.icon"></text>
        </template>
      </el-table-column>
      <el-table-column
        prop="lib_id"
        label="题库ID"
        :width="160"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="lib_name"
        label="题库名称"
        :width="160"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="lib_title"
        label="题库标题"
        :width="160"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="intro"
        label="题库介绍"
        :min-width="240"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="lib_chapter" label="题库章节" :min-width="280" show-overflow-tooltip>
        <template #default="scope">
          <el-tag
            v-for="(item, index) in scope.row?.lib_chapter"
            :key="item"
            :class="'sv-ml-gap-' + index"
            effect="plain"
          >
            {{ item.value }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="banner" label="题库轮播图" :width="240" show-overflow-tooltip>
        <template #default="scope">
          <view v-if="scope.row.banner?.length > 0">
            <el-image
              v-for="(item, index) in scope.row.banner"
              style="width: 30px; height: 20px; margin-right: 2px"
              :src="item.url"
              :preview-src-list="scope.row.banner.map((it) => it.url)"
              :initial-index="index"
              fit="cover"
              preview-teleported
            />
          </view>
        </template>
      </el-table-column>
      <el-table-column
        prop="befit"
        label="题库范围"
        :width="200"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="origin"
        label="题库来源"
        :width="200"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="total"
        label="题库试题量"
        align="center"
        :width="160"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="comment"
        label="题库备注"
        :min-width="240"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="profession[0].profession_name"
        label="所属职业"
        :width="160"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="price" label="定价(分)" :width="200">
        <template #default="scope">
          {{ scope.row.price }}分
          <text class="text-cyan">= {{ convertFenToYuan(scope.row.price) }}元</text>
        </template>
      </el-table-column>
      <el-table-column prop="discount" label="折扣(分)" :width="200">
        <template #default="scope">
          {{ scope.row.discount }}分
          <text class="text-cyan">= {{ convertFenToYuan(scope.row.discount) }}元</text>
        </template>
      </el-table-column>
      <el-table-column label="售价(分)" :width="200">
        <template #default="scope">
          {{ scope.row.price - scope.row.discount }}分
          <text class="text-cyan">
            = {{ convertFenToYuan(scope.row.price - scope.row.discount) }}元
          </text>
        </template>
      </el-table-column>
      <el-table-column
        prop="sell_num"
        label="销售量"
        align="center"
        :width="140"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="fav_num"
        label="收藏量"
        align="center"
        :width="140"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="vip" align="center" label="VIP特权" :width="160">
        <template #default="scope">
          <el-tag :type="vipLibDict[scope.row.vip].type" effect="dark">
            {{ vipLibDict[scope.row.vip].text }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="配置" align="center" :width="160" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button text size="small" :icon="EditPen" @click="edit(scope.row)">编辑</el-button>
            <el-button text size="small" :icon="Delete" @click="del(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <view class="sv-pagination">
      <sv-pagination
        :pagingParams="dataParams"
        :total="total"
        @update:page-size="handleSizeChange"
        @update:current-page="handleCurrentChange"
      />
    </view>
    <!-- 表单抽屉弹窗 -->
    <sv-form
      v-model="showForm"
      :form-init="formInit"
      :form-mode="formMode"
      @submit="submitForm"
    ></sv-form>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import SvForm from './components/sv-form/sv-form.vue'
import SvTableHeader from './components/sv-table-header/sv-table-header.vue'
import { RefreshRight, Plus, EditPen, Delete, View, Hide } from '@element-plus/icons-vue'
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
import { libList, libAdd, libDelete, libUpdate } from '@/service/api/lib'
import { useSysStore } from '@/store/sys'
import { isEmpty } from 'lodash-es'
import { convertFenToYuan } from '@/uni_modules/sv-exam-plus/utils'

const showHeader = ref(useSysStore().platform == 'pc') // 头部筛选栏显示
const tableData = ref([]) // 菜单表格
const loading = ref(false) // 表格loading
const dataParams = ref({ pagesize: 20, pagenum: 1 }) // 筛选参数
const total = ref(0) // 表格总数
const showForm = ref(false) // 显示表单
const formInit = ref({}) // 表单初始值
const formMode = ref('') // 表单模式 add / edit

const vipLibDict = {
  undefined: { text: '普通题库', type: 'info' },
  0: { text: '普通题库', type: 'info' },
  1: { text: 'VIP特权', type: 'success' },
}

// 初始获取表格数据
handleTable(dataParams.value)

async function handleTable(params) {
  loading.value = true

  const dataRes = await libList(params)
  tableData.value = dataRes.data || []
  total.value = dataRes.total || 0

  if (!dataRes.success) {
    ElMessage({
      message: dataRes?.message || dataRes?.error?.message,
      type: 'warning'
    })
  }

  loading.value = false
}

// 刷新
function refresh() {
  tableData.value = [] // 置空数据
  handleTable(dataParams.value)
}

// 新增
function add() {
  formInit.value = {} // 置空参数
  formMode.value = 'add'
  showForm.value = true
}

// 编辑
function edit(item) {
  formInit.value = item // 携带参数
  formMode.value = 'edit'
  showForm.value = true
}

// 提交表单
async function submitForm(e) {
  let result = {}
  switch (e.mode) {
    case 'add':
      // 新增添加
      result = await libAdd(e.data)
      break
    case 'edit':
      // 编辑更新
      result = await libUpdate(e.data)
      break
  }

  if (result.success) {
    ElNotification({
      title: 'Success',
      message: result?.message,
      type: 'success'
    })

    refresh()
  } else {
    ElNotification({
      title: 'Error',
      message: result?.message || result?.error?.message,
      type: 'error'
    })
  }
}

// 删除
function del(item) {
  const { lib_name, lib_id } = item
  ElMessageBox.confirm(`确认删除${lib_name}吗？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 确认删除操作
      const deleteRes = await libDelete({ lib_id })
      ElMessage({
        type: 'success',
        message: deleteRes?.message || deleteRes?.error?.message
      })

      refresh()
    })
    .catch(() => {})
}

// 多选
const batchSelection = ref([])
function handleSelectionChange(e) {
  batchSelection.value = e.map((item) => item.lib_id)
}

// 批量删除
function selectionRemove() {
  if (isEmpty(batchSelection.value)) return

  ElMessageBox.confirm(`确认批量删除所选项吗？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 确认批量删除操作
      const deleteRes = await libDelete({
        lib_id: batchSelection.value
      })

      ElMessage({
        type: 'success',
        message: deleteRes?.message || deleteRes?.error?.message
      })

      refresh()
    })
    .catch(() => {})
}

// 头部筛选栏筛选条件
async function submitFilter(e) {
  Object.assign(dataParams.value, e)
  handleTable(dataParams.value)
}

// 分页
function handleSizeChange(e) {
  dataParams.value.pagesize = e
  handleTable(dataParams.value)
}
function handleCurrentChange(e) {
  dataParams.value.pagenum = e
  handleTable(dataParams.value)
}
</script>

<style lang="scss"></style>
